package org.dingyom.gift.userDetailService;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.dingyom.gift.clients.EmployeeClient;
import org.dingyom.gift.clients.UserClient;
import org.dingyom.gift.context.UserContextInfo;
import org.dingyom.gift.domain.Employee;
import org.dingyom.gift.domain.LoginUser;
import org.dingyom.gift.domain.Permission;
import org.dingyom.gift.exception.asserts.Assert;
import org.dingyom.gift.exception.code.StatusCode;
import org.dingyom.gift.mapper.LoginUserMapper;
import org.dingyom.gift.mapper.PermissionMapper;
import org.dingyom.gift.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private LoginUserMapper loginUserMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private UserClient userClient;
    @Autowired
    private EmployeeClient employeeClient;
    /**
     * 加载数据库中的认证信息：用户名 密码 用户的权限列表
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //通过用户名or电话号码or邮箱 查询出用户信息
        List<LoginUser> loginUsers = loginUserMapper.selectList(new EntityWrapper<LoginUser>()
                .eq("username", username)
                .or()
                .eq("tel", username)
                .or()
                .eq("email", username));
        //断言loginUser不是空
        Assert.assertListNotEmpty(loginUsers, StatusCode.CODE_400_USERNAMEORPASSWORD_ERROR);
        LoginUser loginUser = loginUsers.get(0);
        UserContextInfo contextInfo = new UserContextInfo();
        contextInfo.setLoginUserId(loginUser.getId());
        contextInfo.setLoginUsername(loginUser.getUsername());

        ArrayList<GrantedAuthority> authorities = new ArrayList<>();//存放用户的权限列表
        /*用loginUser的Type来确定是用户还是员工 1表示员工 0表示用户*/
        if (loginUser.getType()==1){
            //查询员工信息
            AjaxResult ajaxByLoginId = employeeClient.getByLoginId(loginUser.getId());
            if (ajaxByLoginId.isSuccess()){
                String str = (String) ajaxByLoginId.getResultObj();
                Employee employee = JSONObject.parseObject(str, Employee.class);
                contextInfo.setUserId(employee.getId());
                contextInfo.setUsername(employee.getUsername());
            }
            //员工才需要权限 查询用户权限列表
            List<Permission> permissions = permissionMapper.selectPermissionByUserId(loginUser.getId());

            permissions.forEach(permission -> {
                System.out.println("用户："+loginUser.getUsername()+" 加载权限："+permission.getSn());
                authorities.add(new SimpleGrantedAuthority(permission.getSn()));
            });
        }else {
            AjaxResult ajaxResultbyId = userClient.getByLoginId(loginUser.getId());
            if (ajaxResultbyId.isSuccess()) {
                String str = (String)
                        ajaxResultbyId.getResultObj();
                org.dingyom.gift.domain.User user =
                        JSONObject.parseObject(str, org.dingyom.gift.domain.User.class);
                contextInfo.setUserId(user.getId());
                contextInfo.setUsername(user.getUsername());
            }
        }


        String password = loginUser.getPassword();

//        User user = new User(username,password,authorities);//username 可以换成用户信息转换的json字符串
        User user = new User(JSONObject.toJSONString(contextInfo),password,authorities);

        return user;
    }
}
